package com.smartrobot.smartrobot.pagerHolder;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.smartrobot.smartrobot.Common.Common;
import com.smartrobot.smartrobot.Common.CommonFunc;
import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.activity.SocialAddActivity;
import com.smartrobot.smartrobot.adapter.FriendViewAdapter;
import com.smartrobot.smartrobot.circle.FriendList;
import com.smartrobot.smartrobot.circle.commonData;
import com.smartrobot.smartrobot.logToSdCard.LogToSd;
import com.smartrobot.smartrobot.pojo.circleDetailPojo;
import com.smartrobot.smartrobot.pojo.getFriendListPojo;
import com.smartrobot.smartrobot.pojo.saveFriendListPojo;
import com.smartrobot.smartrobot.util.FileUtil;
import com.smartrobot.smartrobot.util.HttpUtil;
import com.smartrobot.smartrobot.util.ImageLoaderApi;
import com.smartrobot.smartrobot.util.PeopleRegisterMsg;
import com.smartrobot.smartrobot.util.User;
import com.smartrobot.smartrobot.view.ToastCustom;
import com.smartrobot.smartrobot.view.UnScrollViewPager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SocialCirlePagerHolder1 implements BasePagerHolder,OnClickListener {

	private View view;
	private static Context context;
	private boolean isFirst = true;
//    private boolean isCircleFirst = true;

	private List<View> views;
	private View myCircle,circleDetail,circleItem;
	private UnScrollViewPager uViewPager;
	private RelativeLayout myCirclelayout,circleDetaillayout,circleItemLayout,myBarberLayout;
    private TextView myCircleTxt,circleDetailTxt;
    private ImageView myCircleLine,circleDetailLine;

	private Button addFirend;
    private static ProgressBar progressBar;
    private ListView my_barber_list,my_friend_list,my_circle_friend_list;
    private FriendViewAdapter friendAdapter,barberAdapter,circleAdapter;
    private static  Handler getFriendListHandler ;
    private final Handler readFileHandler = new Handler();
    private FriendList friendList ;
    private static boolean  isGettingFriendList = false;
    private static boolean isGettingCircleDetail = false;

    private TextView progressText;

    List<getFriendListPojo> f_list,c_list,b_list;
    circleDetailPojo c_pojo;


    private final static int RETURN_FROM_ADD_ACTIVITY = 0;

    public SocialCirlePagerHolder1(Context context, View view) {
		this.context = context;
		this.view = view;
	}



    public void initView(){

        if(isFirst){
            Log.e("==================is first========================","is first");
            isFirst = false;

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

//            myCirclelayout = (RelativeLayout)view.findViewById(R.id.social_circle_my_circle);
//            circleDetaillayout = (RelativeLayout)view.findViewById(R.id.social_circle_social_detail);
//            myCircleTxt = (TextView)view.findViewById(R.id.social_circle_my_circle_txt);
//            myCircleLine = (ImageView)view.findViewById(R.id.social_circle_my_circle_line);
//            circleDetailTxt = (TextView)view.findViewById(R.id.social_circle_social_detail_txt);
//            circleDetailLine = (ImageView)view.findViewById(R.id.social_circle_social_detail_line);
//            uViewPager = (UnScrollViewPager)view.findViewById(R.id.social_circle_UnScrollViewPager);
            addFirend = (Button)view.findViewById(R.id.social_circle_add_friend);
            progressBar = (ProgressBar)view.findViewById(R.id.getFriendListLoading);
//            progressText = (TextView)view.findViewById(R.id.social_circle_progressText);
            myCircle = LayoutInflater.from(context).inflate(R.layout.page_social_circle_my_circle, null);//我的圈子
            my_barber_list = (ListView)view.findViewById(R.id.my_barber_list);
            my_friend_list = (ListView)view.findViewById(R.id.my_friend_list);
            my_circle_friend_list = (ListView)myCircle.findViewById(R.id.circle_friend_list);
            myBarberLayout = (RelativeLayout)myCircle.findViewById(R.id.top1);
            myBarberLayout.setVisibility(View.GONE);

            circleItem = LayoutInflater.from(context).inflate(R.layout.page_social_circle_adapter_item,null);
            circleItemLayout = (RelativeLayout)circleItem.findViewById(R.id.circle_friend_adapter);

            circleDetail = LayoutInflater.from(context).inflate(R.layout.page_social_circle_circle_detail, null);//圈子详情


            f_list = new ArrayList<getFriendListPojo>();
            b_list = new ArrayList<getFriendListPojo>();
            c_list = new ArrayList<getFriendListPojo>();

            getFriendListHandler = new changeFriendListHandler();

            views = new ArrayList<View>();
            views.add(myCircle);
            views.add(circleDetail);


            ImageLoader.getInstance().init(ImageLoaderApi.getImageLoaderConfig(context));

            initAdapter();


            // 为viewpager创建adapter
            PagerAdapter pagerAdapter = new PagerAdapter() {

                @Override
                public boolean isViewFromObject(View view, Object object) {
                    // TODO Auto-generated method stub
                    return view == object;
                }

                @Override
                public int getCount() {
                    // TODO Auto-generated method stub
                    return views.size();
                }

                @Override
                public Object instantiateItem(View container, int position) {
                    ((ViewPager) container).addView(views.get(position), 0);
                    return views.get(position);
                }

                @Override
                public void destroyItem(View container, int position, Object object) {
                    ((ViewPager) container).removeView(views.get(position));
                }

            };





//            uViewPager.setScrollView(m_circle_scroll);
            uViewPager.requestDisallowInterceptTouchEvent(true);
            uViewPager.setAdapter(pagerAdapter);
            uViewPager.setCurrentItem(0);
            myCircleSelect();
            circleDetailLostSelect();
            uViewPager.setOffscreenPageLimit(2);

            myCirclelayout.setOnClickListener(SocialCirlePagerHolder1.this);
            circleDetaillayout.setOnClickListener(SocialCirlePagerHolder1.this);
            addFirend.setOnClickListener(SocialCirlePagerHolder1.this);

            uViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i2) {

            }

            @Override
            public void onPageSelected(int i) {

                if(i == 0){

                    myCircleSelect();
                    circleDetailLostSelect();


                }

                if(i == 1){
                    myCircleLostSelect();
                    circleDetailSelect();
                }

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });


            initAdapter();
            getCircleMsgFromLocal();
            progressText.setVisibility(View.GONE);



            return;

                }
            },500);

        }

    }


    /*获取朋友列表*/
    protected void getCircleMsgFromLocal() {

        Thread t = new Thread() {
            public void run() {
                try{
                    Thread.sleep(1500);
                    Log.e("=======用户的id",User.getInstance().getId());
                    saveFriendListPojo list = (saveFriendListPojo)FileUtil.ReadCircleMsgFromFile(CommonFunc.stringToMD5(User.getInstance().getId() + Common.f_circle_friend),context); //处理得到结果了，这里一些内容保存在主类的成员变量中
                    if(list!=null){
                        b_list = list.getBarberList();
                        f_list = list.getFriendList();
                        c_list = list.getCircleList();
                        readFileHandler.post(updateUiFromLocal); //告诉UI线程可以更新结果了
                    }else{
                        readFileHandler.post(updateUiFromServer); //告诉UI线程可以更新结果了

                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }

    final Runnable updateUiFromLocal = new Runnable() {
        public void run() {
            adapterChange();
            getCircleDetail();
        }
    };

    final Runnable updateUiFromServer = new Runnable() {
        @Override
        public void run() {
            getFriend();
            getCircleDetail();
        }
    };



    public void getFriend(){
        if(!isGettingFriendList){
            progressBar.setVisibility(View.VISIBLE);
            friendList  = new FriendList();
            friendList.getFriendList(getFriendListHandler,context);
            isGettingFriendList = true;
        }
    }

    /*获取朋友圈详情*/
    public void getCircleDetail(){
        if(!isGettingCircleDetail){
            progressBar.setVisibility(View.VISIBLE);
            friendList  = new FriendList();
            friendList.getCircleDetail(getFriendListHandler,context);
            isGettingCircleDetail = true;
        }
    }

    /*提醒更新*/
    public void adapterChange(){
        barberAdapter.notifyChange(b_list,my_barber_list);
        friendAdapter.notifyChange(f_list,my_friend_list);
        circleAdapter.notifyChange(c_list,my_circle_friend_list);
    }



	@Override
	public void setView(View view) {
		
	}

	@Override
	public View getView() {
		return view;
	}
	




	@Override
	public void onClick(View v) {
		
		
	   switch(v.getId()){
//	   case R.id.social_circle_my_circle:
//           myCircleSelect();
//           circleDetailLostSelect();
//		   uViewPager.setCurrentItem(0);
//		   break;
//	   case R.id.social_circle_social_detail:
//           myCircleLostSelect();
//           circleDetailSelect();
//		   uViewPager.setCurrentItem(1);
//		   break;
	   case R.id.social_circle_add_friend:
           Intent intent = new Intent();
           intent.setClass(context,SocialAddActivity.class);
//           MainActivity_temp.instance.startActivityForResult(intent, RETURN_FROM_ADD_ACTIVITY);
		   break;
	   }
	}


    public static  void changeFriendList(int requestCode, int resultCode, Intent data){
        Log.e("==============================从新改变朋友列表=======================","");
        switch (requestCode){

            case RETURN_FROM_ADD_ACTIVITY:
            {
                if(resultCode == 1) {//返回成功

                    progressBar.setVisibility(View.VISIBLE);

                    FriendList friendList  = new FriendList();
                    friendList.getFriendList(getFriendListHandler,context);
                    isGettingFriendList = true;

                    friendList.getCircleDetail(getFriendListHandler,context);
                    isGettingCircleDetail = true;
                }
            }

        }

    }


    //handle 处理
    class changeFriendListHandler extends Handler {

        @Override
        public void dispatchMessage(Message msg) {

            //链接服务器失败
            if(msg.what == commonData.CAN_NOT_CONNECT_SERVER_CODE){

                ToastCustom.showToast(context,msg.obj.toString());
                progressBar.setVisibility(View.GONE);
                isGettingFriendList = false;
                isGettingCircleDetail = false;
                return;
            }

            if(msg.what==commonData.SHOW_TIP_CODE){
                ToastCustom.showToast(context,msg.obj.toString());
                progressBar.setVisibility(View.GONE);
                isGettingFriendList = false;
                isGettingCircleDetail = false;
                return;
            }

            //获取好友列表成功
            if(msg.what == commonData.GET_FRIEND_LIST_SUCCESS_CODE)
            {
                try{
                    progressBar.setVisibility(View.GONE);
                    Map<String, Object> f_pojo_map = new HashMap<String, Object>();
                    f_pojo_map = (Map<String,Object>)msg.obj;

                    f_list = (ArrayList<getFriendListPojo>)f_pojo_map.get("friendList");

                    c_list =  (ArrayList<getFriendListPojo>)f_pojo_map.get("customerList");

                    b_list =  (ArrayList<getFriendListPojo>)f_pojo_map.get("barberList");

                    String role = f_pojo_map.get("role").toString();

                    if(role.equals("0")){
                        myBarberLayout.setVisibility(View.VISIBLE);
                    }

                    adapterChange();
                    isGettingFriendList = false;

                    //写入文件
                    saveFriendListPojo circleFriends = new saveFriendListPojo(b_list,f_list,c_list);
                    FileUtil.saveCircleMsgToFile(circleFriends,CommonFunc.stringToMD5(User.getInstance().getId()+Common.f_circle_friend),context);


                }catch (Exception e){
                        e.printStackTrace();
                        LogToSd.debug(e.getMessage());
                }

                return;
            }

            //获取好友失败
            if(msg.what == commonData.GET_FRIEND_LIST_FAIL_CODE)
            {
                isGettingFriendList = false;
                progressBar.setVisibility(View.GONE);
                return;
            }


            //获取圈子详情成功
            if(msg.what == commonData.GET_CIRCLE_DETAIL_SUCCESS_CODE){
                c_pojo = new circleDetailPojo();
                c_pojo = (circleDetailPojo)msg.obj;
                setCircleDetail();
                isGettingCircleDetail = false;

                return;
            }

            //获取圈子详情失败
            if(msg.what == commonData.GET_CIRCLE_DETAIL_FAIL_CODE){
                progressBar.setVisibility(View.GONE);
                isGettingCircleDetail = false;
                return;
            }



            //数据异常
            if(msg.what ==commonData.DATA_ERROR_CODE){
                progressBar.setVisibility(View.GONE);
                isGettingCircleDetail = false;
                isGettingFriendList = false;
                return;
            }

            //用户未登录
            if(msg.what==commonData.USE_NOT_LOGIN_CODE){
                //帮组用户登录
                isGettingCircleDetail = false;
                isGettingFriendList = false;
                int flag = msg.arg1;
                if (User.getInstance() != null&&!User.getInstance().getId().equals("未填写") ) {
                    HttpUtil.apiLogin(context, new PeopleRegisterMsg(User.getInstance().getPhone(), User.getInstance().getPwd()), getFriendListHandler, flag);

                } else if (User.getUserInfo(context)&&!User.getInstance().getId().equals("未填写")) {
                    HttpUtil.apiLogin(context, new PeopleRegisterMsg(User.getInstance().getPhone(), User.getInstance().getPwd()), getFriendListHandler,flag);
                } else {
                    ToastCustom.showToast(context, "请登录！");
                    progressBar.setVisibility(View.GONE);
                }
                return;
            }

            if(msg.what==HttpUtil.LOGIN_SUCCESS){
                getFriend();
                getCircleDetail();
            }

        }
    }


   public void setCircleDetail(){

       String showName = c_pojo.getCircleMasterPhone();
       String nickName = c_pojo.getCircleMasterNickName();
       String reName = c_pojo.getCircleMasterName();

       if(nickName!=null&&!nickName.equals("")){
           showName = nickName;
       }else if(reName!=null&&!reName.equals("")){
           showName = reName;
       }
       ((TextView)circleDetail.findViewById(R.id.circleMaster)).setText(showName);
       ((TextView)circleDetail.findViewById(R.id.userCount)).setText(c_pojo.getUserCount());
       progressBar.setVisibility(View.GONE);
   }


   public  void initAdapter(){
       try{
           f_list = new ArrayList<getFriendListPojo>();
           c_list = new ArrayList<getFriendListPojo>();
           b_list = new ArrayList<getFriendListPojo>();
           barberAdapter = new FriendViewAdapter(context,b_list);
           circleAdapter = new FriendViewAdapter(context,c_list);
           friendAdapter = new FriendViewAdapter(context,f_list);
           my_barber_list.setAdapter(barberAdapter);
           my_friend_list.setAdapter(friendAdapter);
           my_circle_friend_list.setAdapter(circleAdapter);
       }catch (Exception e){
            e.getStackTrace();
           LogToSd.debug("初始化适配器错误");
           Log.e("----------------->",e.getMessage());
       }

   }

    public void myCircleSelect(){

        myCircleTxt.setSelected(true);
        myCircleLine.setSelected(true);

    }

    public void myCircleLostSelect(){

        myCircleTxt.setSelected(false);
        myCircleLine.setSelected(false);

    }

    public void circleDetailSelect(){
        circleDetailTxt.setSelected(true);
        circleDetailLine.setSelected(true);
    }

    public void circleDetailLostSelect(){
        circleDetailTxt.setSelected(false);
        circleDetailLine.setSelected(false);
    }

}
